package com.bridgetree.jubaocrm.ui.project;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.MemberListInterface;
import com.bridgetree.jubaocrm.util.Mmember;
import com.bridgetree.jubaocrm.util.Projects;
/**
 *成员列表
 */
public class XMChildMemberListActivity extends Activity {
	private final String TAG ="XMChildMemberListActivity";
	private Context mContext;
	private PullToRefreshListView xm_of_lv = null;
	private ListView actualListView1 = null;
	private XMChildMemberListAdapter mXMChildMemberListAdapter = null;
	private Projects mProjects;
	private String baojia ;
	private TextView xm_bi_tv_title;
	private String user_id =""; 
	private String token ="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xm_member_list);
		mContext=this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		xm_bi_tv_title =(TextView)findViewById(R.id.xm_bi_tv_title);
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");
			baojia = intent.getExtras().getString("baojia");
		}

		if(baojia.equals("select")){
			xm_bi_tv_title.setText("选择报价人");
		}else{
			xm_bi_tv_title.setText("成员列表");
		}

		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		xm_of_lv=(PullToRefreshListView)findViewById(R.id.xm_ml_lv);
		xm_of_lv.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if(mXMChildMemberListAdapter!=null)
					mXMChildMemberListAdapter.notifyDataSetChanged();
				if(xm_of_lv!=null)
					xm_of_lv.onRefreshComplete();
			}
		});

		xm_of_lv.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				//				if(firstVisibleItem+visibleItemCount == totalItemCount){
				//					scrollTopBottom=1;
				//				}else if(firstVisibleItem == 0){
				//					scrollTopBottom=0;
				//				}
			}
		});
		actualListView1 = xm_of_lv.getRefreshableView();

		if(mProjects!=null || !baojia.equals("")){
			getMemberListData();
		}

	}

	private void getMemberListData() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			String URL = Network.API_DOMAIN+"/project?project_id="+mProjects.getProject_id() 
			+"&user_id="+user_id+"&token="+token+"&validation="+CRMUserBaseInfo.kValication
			+"&part=members";

			final ProgressDialog progressDialog = ProgressDialog.show(this, "网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {  
						@Override
						public void onResponse(JSONObject response) {
							//							System.out.println("成员列表 response="+response);  
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								MemberListInterface mMemberListInterface = new MemberListInterface();
								if (!response.isNull("project")) {
									JSONObject project = new JSONObject(response.getString("project"));
									Projects mProjects = new Projects();
									if (!project.isNull("project_id")) {
										String project_id = project.getString("project_id");
										mProjects.setProject_id(project_id);
									}
									if (!project.isNull("group_id")) {
										String group_id = project.getString("group_id");
										mProjects.setGroup_id(group_id);
									}
									if (!project.isNull("members")) {
										org.json.JSONArray jsonArr;
										List<Mmember> mMmembers = new ArrayList<Mmember>();
										jsonArr = project.getJSONArray("members");
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr.length(); i++) {
												Mmember mMmember = new Mmember();
												JSONObject jsonObj2 = jsonArr.getJSONObject(i);
												if (!jsonObj2.isNull("fullname")) {
													String fullname = jsonObj2.getString("fullname");
													mMmember.setFullname(fullname);
												}
												if (!jsonObj2.isNull("user_id")) {
													String user_id = jsonObj2.getString("user_id");
													mMmember.setUser_id(user_id);
												}
												mMmembers.add(mMmember);
											}
										}
										mProjects.setMembers(mMmembers);
									}
									mMemberListInterface.setProject(mProjects);
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														mLoginError.setDesc(desc);
														openDailog("失败提示", desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
											mMemberListInterface.setErrors(mLoginError);
										}
									}
								}
								mXMChildMemberListAdapter = new XMChildMemberListAdapter(mContext,mMemberListInterface.getProject().getMembers());
								actualListView1.setAdapter(mXMChildMemberListAdapter);
								if (xm_of_lv != null) {
									xm_of_lv.onRefreshComplete();
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					},
					new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {  
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");  
						}  
					});  
			requestQueue.add(jsonObjectRequest); 
		}
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	class XMChildMemberListAdapter extends BaseAdapter {
		private Context mContext;
		private List<Mmember> DrugstoreDataList = null;
		private LayoutInflater listContainer; // 视图容器

		public final class ListItemView { // 自定义控件集合
			public TextView xm_12_item_tv; 
			public ImageView xm_12_item_iv; 
			public RelativeLayout RelativeLayouts; 
		}

		public XMChildMemberListAdapter(Context mContext, List<Mmember> list) {
			this.mContext= mContext;
			this.DrugstoreDataList = list;
			listContainer = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			if (DrugstoreDataList != null) {
				return DrugstoreDataList.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return DrugstoreDataList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ListItemView listItemView = null;
			if (convertView == null) {
				listItemView = new ListItemView();
				// 获取list_item布局文件的视图
				convertView = listContainer.inflate(R.layout.xm_12_item, null);
				// 获取控件对象
				listItemView.RelativeLayouts = (RelativeLayout) convertView.findViewById(R.id.RelativeLayouts);
				listItemView.xm_12_item_tv = (TextView) convertView.findViewById(R.id.xm_12_item_tv);
				listItemView.xm_12_item_iv = (ImageView) convertView.findViewById(R.id.xm_12_item_iv);
				// 设置控件集到convertView
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}
			listItemView.xm_12_item_tv.setText((String) DrugstoreDataList.get(position).getFullname());
			listItemView.xm_12_item_iv.setVisibility(View.GONE);

			if(null != baojia && baojia.equals("select")){
				listItemView.RelativeLayouts.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						XMChildAddBaoActivity.peopleName=(String) DrugstoreDataList.get(position).getFullname();
						finish();
					}
				});
			}
			return convertView;
		}

	}
}
